import _ from 'lodash';
import * as api from '@/services/SupplyPlanMgr';
import * as utils from '../../utils/treeUtils';

const Model = {
  namespace: 'ConfirmProjectItems',
  state: {
    all: [],
    searched: [],
    expandedRowKeys: [],
    searchItems: {},
  },
  effects: {
    *init({ payload, callback }, { call, put }) {
      yield put({
        type: 'save',
        payload: {
          all: [],
          searched: [],
          expandedRowKeys: [],
          searchItems: {},
        },
      });
      let response = [];
      if (payload.params.id) {
        response = yield call(api.supplyConfirmDetailUsingGET, payload);
      } else {
        response = yield call(api.supplyConfirmDetailTwoUsingGET, payload);
      }
      if (response && response.data && !_.isEmpty(response.data)) {
        const all = response.data;
        let searchItems = [];
        if (!payload.params.code) {
          searchItems = utils.getSearchItems(all);
        }
        // 获取展开的列key
        const expandedRowKeys = utils.getExpandedRowKeys(all);
        const searched = utils.buildTree(all);
        yield put({
          type: 'save',
          payload: { all, searched, expandedRowKeys, searchItems },
        });
      }
      if (callback) callback(response && response.data ? response.data : []);
    },
  },
  reducers: {
    save(state, action) {
      return {
        ...state,
        ...action.payload,
      };
    },
  },
};
export default Model;
